package siemenss7smart

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	// "sync"
)

// var (
// 	PLCMap = make(map[string]PLCLinkInfo)
// )

// var fileLocker sync.Mutex

// PLCManagerStruct Device的map整体状态
type PLCManagerStruct struct {
	Devices map[string]Device
}

// PLCManager 缓存了所有Device的状态、数据和方法
var PLCManager PLCManagerStruct

// LoadConfig 读取config目录下的配置信息，json格式
func LoadConfig(configFilePath string) error {

	fileData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return err
	}
	err = json.Unmarshal(fileData, &PLCManager)
	if err != nil {
		return err
	}
	for key, info := range PLCManager.Devices {
		fmt.Printf("key %v\n", key)
		fmt.Printf("value %v \n", info)
	}
	return nil
}

// LinkDevice 连接设备
func LinkDevice(deviceKey string) error {
	deviceInfo, ok := PLCManager.Devices[deviceKey]
	if !ok {
		return errors.New("指定的设备不存在")
	}
	_, err := deviceInfo.Connect()
	return err
}
